﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Practices.ServiceLocation;

namespace AzureToolkit.Engine
{
    internal class MessageHandler<TMessage> : MessageHandlerBase<TMessage>, IMessageHandler where TMessage : IAzureQueueMessage
    {

        public MessageHandler(MessageHandlerSettings settings)
            : base(settings)
        {
        }

        protected override bool Cycle()
        {
            try
            {
                var messages = this.Queue.GetMessages(this.Settings.BatchSize);
                if (messages != null)
                {
                    foreach (var message in messages)
                    {

                        var command = (ICommand<TMessage>)ServiceLocator.Current.GetInstance(Settings.CommandType);
                        var action = new Action<TMessage>(command.Run);
                        ProcessMessages(new TMessage[] { message }, action);
                    }
                }
                Thread.Sleep(this.Settings.IntervalBetweenRuns);
                return messages != null;
            }
            catch (TimeoutException)
            {
                return true;
            }
        }
    }
}
